<template>
  <div class="family-tree">
    <div class="toolbar">
      <el-button-group>
        <el-button @click="handleZoom('in')" :icon="ZoomIn">放大</el-button>
        <el-button @click="handleZoom('out')" :icon="ZoomOut">缩小</el-button>
        <el-button @click="handleReset" :icon="Refresh">重置</el-button>
        <el-button @click="toggleFullscreen" :icon="FullScreen">
          {{ isFullscreen ? '退出全屏' : '全屏' }}
        </el-button>
      </el-button-group>
    </div>
    
    <div class="tree-container" ref="treeContainer">
      <div v-if="loading" class="loading-container">
        <el-empty description="加载中..." v-loading="true" />
      </div>
      <div v-else-if="!treeData || treeData.length === 0" class="empty-container">
        <el-empty description="暂无家族树数据" />
      </div>
      <div v-else class="tree-wrapper" :style="{ transform: `scale(${scale})` }">
        <TreeNode
          v-for="rootNode in treeData"
          :key="rootNode.id"
          :node="rootNode"
          :selected-id="selectedId"
          @node-click="handleNodeClick"
          @view="handleView"
          @edit="handleEdit"
          @add-relative="handleAddRelative"
          @delete="handleDelete"
          @edit-success="fetchFamilyTree"
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useMessage } from '@/hooks/web/useMessage'
import { ZoomIn, ZoomOut, Refresh, FullScreen } from '@element-plus/icons-vue'
import screenfull from 'screenfull'
import TreeNode from './TreeNode.vue'
import * as MembersApi from '@/api/family/members'

const message = useMessage()
const treeContainer = ref()
const isFullscreen = ref(false)
const scale = ref(1)
const selectedId = ref<number | undefined>(undefined)
const treeData = ref<any[]>([])
const loading = ref(false)

// 获取家族树数据
const fetchFamilyTree = async () => {
  loading.value = true
  try {
    const res = await MembersApi.getFamilyTree()
    if (res.code === 0 && res.data) {
      treeData.value = res.data[0]
    } else {
      message.error(res.msg || '获取家族树数据失败')
      treeData.value = []
    }
  } catch (error) {
    console.error('获取家族树数据出错:', error)
    message.error('获取家族树数据失败')
    treeData.value = []
  } finally {
    loading.value = false
  }
}

// 缩放控制
const handleZoom = (type: 'in' | 'out') => {
  const ratio = type === 'in' ? 1.2 : 0.8
  scale.value = Number((scale.value * ratio).toFixed(2))
}

// 重置视图
const handleReset = () => {
  scale.value = 1
  selectedId.value = undefined
}

// 全屏控制
const toggleFullscreen = () => {
  if (screenfull.isEnabled) {
    const element = document.querySelector('.family-tree')
    if (element) {
      screenfull.toggle(element).then(() => {
        isFullscreen.value = !isFullscreen.value
      })
    }
  }
}

// 节点点击事件
const handleNodeClick = (node: any) => {
  console.log('Node clicked:', node)
  selectedId.value = selectedId.value === node.id ? undefined : node.id
}

// 查看详情
const handleView = (node: any) => {
  // TODO: 实现查看详情功能
  message.success(`查看 ${node.name} 的详细信息`)
}

// 编辑信息
const handleEdit = (node: any) => {
  // TODO: 实现编辑功能
  message.success(`编辑 ${node.name} 的信息`)
}

// 添加关系
const handleAddRelative = (payload: { node: any; relationType: string }) => {
  // TODO: 实现添加关系功能
  const { node, relationType } = payload
  message.success(`为 ${node.name} 添加${relationType}关系`)
}

// 删除成员
const handleDelete = async (node: any) => {
  try {
    await MembersApi.deleteMember(node.id)
    message.success(`成员 ${node.name} 已删除`)
    // 刷新家族树
    await fetchFamilyTree()
  } catch (error) {
    message.error(`删除失败: ${error}`)
  }
}

// 暴露fetchFamilyTree方法，以便父组件可以调用
defineExpose({
  fetchFamilyTree
})

// 不在组件挂载时获取数据，而是由父组件调用
</script>

<style scoped>
.family-tree {
  width: 100%;
  height: 100%;
  min-height: 1500PX;
  position: relative;
  background-color: #fff;
  overflow: hidden;
}

.tree-container {
  width: 100%;
  height: 100%;
  padding: 20px;
  overflow: auto;
}

.tree-wrapper {
  transform-origin: center center;
  transition: transform 0.3s;
  display: flex;
  justify-content: center;
  padding: 40px;
  flex-direction: column;
  align-items: center;
}

.loading-container, .empty-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 500px;
  width: 100%;
}

.toolbar {
  position: absolute;
  top: 20px;
  right: 20px;
  z-index: 100;
  background: rgba(255, 255, 255, 0.9);
  padding: 10px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.toolbar .el-button {
  margin: 0 5px;
}

/* 全屏样式 */
:fullscreen .family-tree,
:fullscreen .tree-container {
  height: 100vh;
  width: 100vw;
}

/* 兼容 webkit 浏览器 */
:-webkit-full-screen .family-tree,
:-webkit-full-screen .tree-container {
  height: 100vh;
  width: 100vw;
}
</style> 
